package com.eshop.web.page;

import com.eshop.web.page.template.BaseTemplate;
import org.apache.wicket.authroles.authentication.AuthenticatedWebSession;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.markup.html.form.StatelessForm;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.CompoundPropertyModel;

/**
 * Created by IntelliJ IDEA.
 * User: Sergey
 * Date: 17.10.13
 * Time: 1:05
 * To change this template use File | Settings | File Templates.
 */
public class SignInPage extends BaseTemplate {
    public SignInPage() {
        final LoginForm form = new LoginForm("loginForm");
        mainMarkupContainer.add(form);
    }

    private static class LoginForm extends Form {

        //private static final long serialVersionUID = -6826853507535977683L;

        private String username;
        private String password;

        public LoginForm(String id) {
            super(id);
            setModel(new CompoundPropertyModel(this));
            add(new Label("usernameLabel", "Login"/*getString("login.username.label", null, "Username")*/));
            add(new RequiredTextField("username"));
            add(new Label("passwordLabel", "Password" /*getString("login.password.label", null, "Username")*/));
            add(new PasswordTextField("password"));
            add(new FeedbackPanel("feedback"));
        }

        @Override
        protected void onSubmit() {
            AuthenticatedWebSession session = AuthenticatedWebSession.get();
            if (session.signIn(username, password)) {
                setDefaultResponsePageIfNecessary();
            } else {
                error("Bad credentials!" /*getString("login.failed.badcredentials")*/);
            }
        }

        private void setDefaultResponsePageIfNecessary() {
            if (!continueToOriginalDestination()) {
                setResponsePage(getApplication().getHomePage());
            }
        }
    }
}
